package com.common.converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.upload.FormFile;

import com.common.util.SystemUtil;


/**
 * This class is converts a java.util.Date to a String
 * and a String to a java.util.Date. 
 */
public class DateConverter implements Converter {
    private static String DATE_FORMAT_INPUT = SystemUtil.getString("date.format.input","ddMMyyyy");
    private static String DATE_FORMAT_DISPLAY = SystemUtil.getString("date.format.display","dd-MMM-yyyy");

    public Object convert(Class type, Object value) {
        if (value == null) {
            return null;
        } else if (type == Date.class) {
            return convertToDate(type, value);
        } else if (type == String.class) {
            return convertToString(type, value);
        } else if( type == FormFile.class) {
            return null;
        }
        throw new ConversionException("Could not convert " +
                                      value.getClass().getName() + " to " +
                                      type.getName());
    }

    protected Object convertToDate(Class type, Object value) {
        DateFormat df = new SimpleDateFormat(DATE_FORMAT_INPUT, Locale.ENGLISH);
        if (value instanceof String) {
            try {
                if (StringUtils.isEmpty(value.toString())) {
                    return null;
                }

                return df.parse((String) value);
            } catch (Exception pe) {
                throw new ConversionException("Error converting String to Date");
            }
        }

        throw new ConversionException("Could not convert " +
                                      value.getClass().getName() + " to " +
                                      type.getName());
    }

    protected Object convertToString(Class type, Object value) {
        DateFormat df = new SimpleDateFormat(DATE_FORMAT_DISPLAY, Locale.ENGLISH);
        if (value instanceof Date) {
            try {
                return df.format(value);
            } catch (Exception e) {
                throw new ConversionException("Error converting Date to String");
            }
        }

        return value.toString();
    }
}
